package org.emf.plugins.tomcatlauncher;

import java.io.IOException;
import java.net.UnknownHostException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.emf.plugins.tomcatlauncher.server.KyahClient;
import org.emf.plugins.tomcatlauncher.server.KyahRequest.Command;
import org.emf.plugins.tomcatlauncher.server.KyahResponse.Token;
import org.emf.plugins.tomcatlauncher.server.KyahResponse;

/**
 * Stop tomcat.
 * @goal stop
 */
public final class StopTomcatMojo extends AbstractMojo {

    /** Mojo execution. */
    public void execute() throws MojoExecutionException {
        KyahClient client = new KyahClient();
        try {
            KyahResponse response = client.connect();
            if (Token.ESTABLISHED.equals(response.getToken())) {
                getLog().info(">>> Connection established.");
                getLog().info(">>> Sending stop signal.");
                KyahResponse stopResponse = client.sendMessage(Command.STOP);
                if (!Token.STOP_OK.equals(stopResponse.getToken())) {
                    getLog().error("Could not stop server. " + stopResponse.getToken() + ":" + stopResponse.getMessage());
                }
                getLog().info(">>> Server is down.");
            } else {
                getLog().error("Could not stop server. " + response.getToken() + ":" + response.getMessage());
            }
        } catch (UnknownHostException e) {
            getLog().error("Server not available.", e);
            throw new MojoExecutionException("Server not available.", e);
        } catch (IOException e) {
            getLog().error("Could not stop server.", e);
            throw new MojoExecutionException("Could not stop server.", e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                getLog().error("Could not close client.", e);
            }
        }
    }

}
